package com.etonedu.meals.utils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.drawable.GradientDrawable;
import android.media.AudioManager;
import android.media.ExifInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.view.WindowManager;

import com.blankj.utilcode.util.LogUtils;
import com.etonedu.meals.R;
import com.etonedu.meals.shot.ScreentShotUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.ref.SoftReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Formatter;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import cn.leancloud.AVFile;
//import cn.leancloud.callback.ProgressCallback;


/**
 * Created by Administrator on 2016/11/7.
 */
@SuppressLint("WrongConstant")
public class Utils {
    public static int getAndroidSDKVersion() {
        int version = 0;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
        }
        return version;
    }

    /**
     * 获取图片名称获取图片的资源id的方法
     *
     * @param imageName
     * @return
     */
    public static int getResource(Context ctx, String imageName) {
        int resId = ctx.getResources().getIdentifier(imageName, "drawable",
                ctx.getPackageName());
        return resId;
    }

    public static int getResource(Context ctx, String fileName, String imageName) {
        int resId = ctx.getResources().getIdentifier(imageName, fileName,
                ctx.getPackageName());
        return resId;
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public static String getVersion(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            return "版本号：" + version;
        } catch (Exception e) {
            e.printStackTrace();
            return "版本号: 0.0.0";
        }
    }

    public static String getVersion1(Context context) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(context.getPackageName(),
                    0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "0.0.0";
        }
    }

    public final static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            // 获得MD5摘要算法的 MessageDigest 对象
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            // 使用指定的字节更新摘要
            mdInst.update(btInput);
            // 获得密文
            byte[] md = mdInst.digest();
            // 把密文转换成十六进制的字符串形式
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getDevCode() {
        SharedPreferencesUtil spu = SharedPreferencesUtil.getInstance(x.app());
        String macAddress = getMacAddress();
        return MD5(macAddress);
    }

    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dp2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    public static String getNextDay(String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date date = calendar.getTime();

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        String timeString = sdf.format(date);
        return timeString;
    }

    public static long getUpperDay(String format) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date date = calendar.getTime();

        return date.getTime();
    }

    public static int getCurrWeek() {

        int week = 0;
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(new Date());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {// 周日
            week = 7;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {// 周一
            week = 1;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {// 周二
            week = 2;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {// 周三
            week = 3;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {// 周四
            week = 4;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {// 周五
            week = 5;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {// 周六
            week = 6;
        }

        return week;
    }

    public static String getWeek(Date date) {

        String week = "";
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(date);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {// 周日
            week = "周日";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {// 周一
            week = "周一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {// 周二
            week = "周二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {// 周三
            week = "周三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {// 周四
            week = "周四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {// 周五
            week = "周五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {// 周六
            week = "周六";
        }

        return week;
    }

    public static String getDayByWeek(int week) {
        int currWeek = getCurrWeek();
        if (currWeek - week > 0) {
            long time = getFrontDay(new Date(), (currWeek - week));
            return timestamp2String1(time, "yyyy-MM-dd");
        } else if (currWeek - week < 0) {
            long time = getFrontDay(new Date(), (currWeek - week));
            return timestamp2String1(time, "yyyy-MM-dd");
        } else if (currWeek - week == 0) {
            return timestamp2String1(System.currentTimeMillis(), "yyyy-MM-dd");
        } else {
            return "";
        }
    }

    /**
     * 将px值转换为dip或dp值，保证尺寸大小不变
     *
     * @param pxValue
     * @param scale   （DisplayMetrics类中属性density）
     * @return
     */
    public static int px2dip(float pxValue, float scale) {
        return (int) (pxValue / scale + 0.5f);
    }

    /**
     * 将dip或dp值转换为px值，保证尺寸大小不变
     *
     * @param dipValue
     * @param scale    （DisplayMetrics类中属性density）
     * @return
     */
    public static int dip2px(float dipValue, float scale) {
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 将px值转换为sp值，保证文字大小不变
     *
     * @param pxValue
     * @param fontScale （DisplayMetrics类中属性scaledDensity）
     * @return
     */
    public static int px2sp(float pxValue, float fontScale) {
        return (int) (pxValue / fontScale + 0.5f);
    }

    /**
     * 将sp值转换为px值，保证文字大小不变
     *
     * @param spValue
     * @return
     */
    public static int sp2px(Context context, float spValue) {
        final float fontScale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * fontScale + 0.5f);
    }

    public static boolean isMobileNum(String mobiles) {
        Pattern p = Pattern.compile("^(1[3-9])\\d{9}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    /**
     * 判断List是否为空
     */
    public static boolean listIsNullOrEmpty(Collection<?> list) {
        return list == null || list.isEmpty();
    }

    /**
     * 判断字符串是否为空
     */
    public static boolean isEmpty(String str) {
        return str == null || "".equals(str) || "null".equals(str);
    }

    /**
     * 获取文件名
     */
    public static String getFileName(String filePath) {
        int indexLast = filePath.lastIndexOf("/");

        String name = filePath.substring(indexLast + 1, filePath.length());

        return name;
    }

    /**
     * @return 路径
     */
    public static String getSDPath() {
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()
                .equals(Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if (sdCardExist) {
            sdDir = Environment.getExternalStorageDirectory();//获取跟目录
        }
        if (sdDir != null) {
            return sdDir.toString();
        } else {
            return "/mnt/extsd/179_1";
        }

    }

    //判断sd卡的mp4文件是否存在
    public static boolean isExists(String filePath) {
        File file = new File(filePath);
        return file.exists();
    }

    /**
     * 判断是否为合法IP
     *
     * @return the ip
     */
    public static boolean isIpAddress(String ipAddress) {
//		String ip = "\\b((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\.((?!\\d\\d\\d)\\d+|1\\d\\d|2[0-4]\\d|25[0-5])\\b";
        String ip = "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";
        Pattern pattern = Pattern.compile(ip, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(ipAddress);
        return matcher.matches();
    }

    //获取版本号(内部识别号)
    public static int getVersionCode(Context context) {
        try {
            PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }

    public static String getAppVersion(Context context, String packageName) {
        try {
            PackageManager manager = context.getPackageManager();
            PackageInfo info = manager.getPackageInfo(packageName,
                    0);
            String version = info.versionName;
            return version;
        } catch (Exception e) {
            e.printStackTrace();
            return "0";
        }
    }

    /**
     * 静默安装
     *
     * @param file
     * @return
     */
    public static boolean slientInstall(File file) {
        boolean result = false;
        Process process = null;
        OutputStream out = null;
        try {
            process = Runtime.getRuntime().exec("su");
            out = process.getOutputStream();
            DataOutputStream dataOutputStream = new DataOutputStream(out);
            dataOutputStream.writeBytes("chmod 777 " + file.getPath() + "\n");
            dataOutputStream.writeBytes("LD_LIBRARY_PATH=/vendor/lib:/system/lib pm install -r " +
                    file.getPath());
            // 提交命令
            dataOutputStream.flush();
            // 关闭流操作
            dataOutputStream.close();
            out.close();
            int value = process.waitFor();

            // 代表成功
            if (value == 0) {
                result = true;
            } else if (value == 1) { // 失败
                result = false;
            } else { // 未知情况
                result = false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 把string写入sd卡
     */
    public static void writeToSdCard(String conetent) {
        String path = getSDPath() + "/eton";
        String name = path + "/" + "url.txt";
        File file = new File(path);
        File fileName = new File(name);

        try {

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.mkdirs();
            }
            if (!fileName.exists()) {
                fileName.createNewFile();
            }

            FileWriter fw = new FileWriter(fileName.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(conetent);
            bw.close();

            Log.d("Utils", "Done");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*
     * 参数：conetent 写入内容
     * 参数：fName 文件名
     * 参数：cover 是否覆盖
     */
    public static void writeToSdCard(String conetent, String fName, boolean isCover) {
        String path = getSDPath() + "/eton";
        String name = path + "/" + fName;
        File file = new File(path);
        File fileName = new File(name);

        try {

            // if file doesnt exists, then create it
            if (!file.exists()) {
                file.mkdirs();
            }
            if (!fileName.exists()) {
                fileName.createNewFile();
            }

            FileWriter fw = new FileWriter(fileName.getAbsoluteFile(), isCover);
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(conetent);
            bw.close();

            Log.d("Utils", "写入成功!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String format3(double value) {

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(2);
        /*
         * setMinimumFractionDigits设置成2
         *
         * 如果不这么做，那么当value的值是100.00的时候返回100
         *
         * 而不是100.00
         */
        nf.setMinimumFractionDigits(2);
        nf.setRoundingMode(RoundingMode.HALF_UP);
        /*
         * 如果想输出的格式用逗号隔开，可以设置成true
         */
        nf.setGroupingUsed(false);
        return nf.format(value);
    }

    public static String format5(double value, String format) {
        /*
         * %.2f % 表示 小数点前任意位数 2 表示两位小数 格式后的结果为 f 表示浮点型
         */
        return new Formatter().format(format, value).toString();
    }

    public static String format(double d) {
        double db = d * 100;
        if (db % 100 == 0) {
            String str = format5(d, "%.0f");
            return str;
        } else if (db % 10 == 0) {

            String str = format5(d, "%.1f");
            return str;
        } else {
            return d + "";
        }

    }

    public static String readToSdCard(String fileName) {
        String path = getSDPath() + "/eton";
        String name = path + "/" + fileName;
        File file = new File(name);

        try {
            BufferedReader br = new BufferedReader(new FileReader(file));
            String readline = "";
            StringBuffer sb = new StringBuffer();
            while ((readline = br.readLine()) != null) {
                sb.append(readline);
            }
            br.close();
            Log.d("Utils", "读取成功：" + sb.toString());
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static String readToSdCard(String file, String fileName) {
        String path = getSDPath() + "/" + file;
        String name = path + "/" + fileName;
        File f = new File(name);

        try {
            BufferedReader br = new BufferedReader(new FileReader(f));
            String readline = "";
            StringBuffer sb = new StringBuffer();
            while ((readline = br.readLine()) != null) {
                sb.append(readline);
            }
            br.close();
            Log.d("Utils", "读取成功：" + sb.toString());
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取mac地址
     */
    public static String getMacAddress(Context context) {

        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        String macAddress = manager.getConnectionInfo().getMacAddress();
        return macAddress;
    }

    // 获取有网线的mac地址
    public static String getMacAddress() {
        try {
            return loadFileAsString("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String loadFileAsString(String filePath) throws java.io.IOException {
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead = 0;
        while ((numRead = reader.read(buf)) != -1) {
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    /**
     * 判断是否是json结构
     */
    public static boolean isJson(String value) {
        try {
            if (value.startsWith("[")) {
                new JSONArray(value);
                return true;
            } else if (value.startsWith("{")) {
                new JSONObject(value);
                return true;
            }
            return false;
        } catch (JSONException e) {
            return false;
        }
    }

    /**
     * 获取当前的日期
     * return xx月xx日
     */
    public static String getDate(long currTime) {
        SimpleDateFormat format = new SimpleDateFormat("MM月dd日");

        Date date = new Date(currTime);
        String currDate = format.format(date);

        return currDate;
    }

    /**
     * 判断当前日期是星期几
     *
     * @return dayForWeek 判断结果
     * @Exception 发生异常
     */
    public static String getWeek() {

        String Week = "";
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(new Date());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            Week += "日";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
            Week += "一";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
            Week += "二";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
            Week += "三";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
            Week += "四";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
            Week += "五";
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
            Week += "六";
        }

        return Week;
    }

    // 判断网络是否可用
    public static boolean isConnectInternet(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            return networkInfo.isAvailable();
        }
        return false;
    }

    // 根据当前的时间 判断早上 上午 下午
    public static String getCurrDateSection() {
        Date dTime = new Date();

        DateFormat df = new SimpleDateFormat("HHmm");
        Integer nTime = new Integer(df.format(dTime));
        String helloStr = "晚上好！";
        if ((500 <= nTime) && (nTime < 910)) {
            helloStr = "早上好！";
        } else if ((910 <= nTime) && (nTime < 1200)) {
            helloStr = "上午好！";
        } else if ((1200 <= nTime) && (nTime < 1400)) {
            helloStr = "中午好！";
        } else if ((1400 <= nTime) && (nTime < 1830)) {
            helloStr = "下午好！";
        }
        return helloStr;
    }

    // 判断app是否存在
    public static boolean checkApplication(Context context, String packageName) {
        if (packageName == null || "".equals(packageName)) {
            return false;
        }
        try {
            ApplicationInfo info = context.getPackageManager().getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
            return false;
        }
    }

    /**
     * 判断某个服务是否正在运行的方法
     *
     * @param context
     * @param className 是包名+服务的类名（例如：net.loonggg.testbackstage.TestService）
     * @return true代表正在运行，false代表服务没有正在运行
     */
    public static boolean isServiceWork(Context context, String className) {
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(Integer.MAX_VALUE);

        if (!(serviceList.size() > 0)) {
            return false;
        }

        for (int i = 0; i < serviceList.size(); i++) {
            ActivityManager.RunningServiceInfo serviceInfo = serviceList.get(i);
            ComponentName serviceName = serviceInfo.service;

            if (serviceName.getClassName().equals(className)) {
                return true;
            }
        }
        return false;
    }


    public static String getLocalIpAddress(Context context) {
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return intToIp(ipAddress);
    }

    private static String intToIp(int i) {

        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    /**
     * 得到有限网关的IP地址
     *
     * @return
     */
    public static String getLocalIp() {

        try {
            // 获取本地设备的所有网络接口
            Enumeration<NetworkInterface> enumerationNi = NetworkInterface
                    .getNetworkInterfaces();
            while (enumerationNi.hasMoreElements()) {
                NetworkInterface networkInterface = enumerationNi.nextElement();
                String interfaceName = networkInterface.getDisplayName();
                Log.i("tag", "网络名字" + interfaceName);

                // 如果是有限网卡
                if (interfaceName.equals("eth0")) {
                    Enumeration<InetAddress> enumIpAddr = networkInterface
                            .getInetAddresses();

                    while (enumIpAddr.hasMoreElements()) {
                        // 返回枚举集合中的下一个IP地址信息
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        // 不是回环地址，并且是ipv4的地址
                        if (!inetAddress.isLoopbackAddress()
                                && inetAddress instanceof Inet4Address) {
                            Log.i("tag", inetAddress.getHostAddress() + "   ");

                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }

        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "";

    }

    private void getIP() {}

    public static String timestamp2String(long timestamp) {
        String timeString = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = new Date(timestamp);
            timeString = sdf.format(date);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return timeString;
    }

    public static String timestamp2String1(long timestamp, String format) {
        String timeString = "";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
            Date date = new Date(timestamp);
            timeString = sdf.format(date);
        } catch (Exception e) {
            // TODO: handle exception
        }
        return timeString;
    }

    // 获取当前天的0点整的时间戳
    public static long getCurrDay4Time() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date zero = calendar.getTime();
        return zero.getTime();
    }


    /**
     * 获得屏幕高度
     *
     * @param context
     * @return
     */
    public static int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    /**
     * 获得屏幕宽度
     *
     * @param context
     * @return
     */
    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    /**
     * 拆分集合
     *
     * @param datas
     * @param splitSize
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> spliceArrays(List<T> datas, int splitSize) {
        if (datas == null || splitSize < 1) {
            return null;
        }
        int totalSize = datas.size();
        int count = (totalSize % splitSize == 0) ?
                (totalSize / splitSize) : (totalSize / splitSize + 1);

        List<List<T>> rows = new ArrayList<>();

        for (int i = 0; i < count; i++) {

            List<T> cols = datas.subList(i * splitSize,
                    (i == count - 1) ? totalSize : splitSize * (i + 1));
            rows.add(cols);
        }
        return rows;
    }

    /**
     * 拆分集合
     *
     * @param datas
     * @param splitSize
     * @param <T>
     * @return
     */
    public static <T> List<List<T>> spliceArrays1(List<T> datas, int splitSize) {
        if (datas == null || splitSize < 1) {
            return null;
        }
        int totalSize = datas.size();
        //获取要拆分子数组个数
        int count = (totalSize % splitSize == 0) ?
                (totalSize / splitSize) : (totalSize / splitSize + 1);

        Log.d("Utils", "split count = " + count);

        List<List<T>> rows = new ArrayList();
        for (int i = 0; i < count; i++) {

            int index = i * splitSize;
            List<T> cols = new ArrayList();
            int j = 0;
            while (j < splitSize && index < totalSize) {
                cols.add(datas.get(index++));
                j++;
            }
            rows.add(cols);
        }
        return rows;
    }

    public static <T> List<List<T>> spliceArrays2(List<T> datas, int listCount) {
        if (datas == null || listCount < 1) {
            return null;
        }
        int totalSize = datas.size();
        int splitSize = totalSize / listCount;


        List<List<T>> rows = new ArrayList();
        for (int i = 0; i < listCount; i++) {

            int index = i * splitSize;
            List<T> cols = new ArrayList();
            int j = 0;
            while (j < splitSize && index < totalSize) {
                cols.add(datas.get(index++));
                j++;
            }


            rows.add(cols);
            if (i == listCount - 1) {
                List<T> lastList = rows.get(rows.size() - 1);
                while (index < totalSize) {
                    lastList.add(datas.get(index));
                    index++;
                }
            }
        }
        return rows;
    }

    /**
     * 利用正则表达式判断字符串是否是数字
     *
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (TextUtils.isEmpty(str)) {
            return false;
        }
        try {
            new Integer(str.trim());
            return true;
        } catch (Exception e) {
            return false;
        }

    }

    /**
     * @param strokeWidth 边框宽度
     * @param roundRadius 圆角半径
     * @param strokeColor 边框颜色
     * @param fillColor   内部填充颜色
     * @return GradientDrawable
     */
    public static GradientDrawable getShape(int strokeWidth, int roundRadius, String strokeColor, String fillColor) {
        GradientDrawable gd = new GradientDrawable();//创建drawable
        gd.setColor(Color.parseColor(fillColor));
        gd.setCornerRadius(roundRadius);
        gd.setStroke(strokeWidth, Color.parseColor(strokeColor));
        return gd;
    }

    // 飞机版课程边框
    public static GradientDrawable getPlaneWhiteShape(int strokeWidth, int roundRadius) {
//        GradientDrawable gd = getShape(strokeWidth, roundRadius, "#d6d6d6", "#aaffffff");
        GradientDrawable gd = getShape(strokeWidth, roundRadius, "#d6d6d6", "#ffffffff");
        return gd;
    }

    public static GradientDrawable getPlaneBlackShape(int strokeWidth, int roundRadius) {
//        GradientDrawable gd = getShape(strokeWidth, roundRadius, "#d6d6d6", "#aaffffff");
        GradientDrawable gd = getShape(strokeWidth, roundRadius, "#99999999", "#ffffffff");
        return gd;
    }

    // base64加密
    public static String base64Encode(String msg) {
        return Base64.encodeToString(msg.getBytes(), Base64.DEFAULT);
    }

    // base64加密
    public static String base64Encode(byte[] msg) {
        return Base64.encodeToString(msg, Base64.DEFAULT);
    }

    // base解密
    public static String base64Decode(String msg) throws Exception {
        return new String(Base64.decode(msg.getBytes(), Base64.DEFAULT));
    }

    // base解密
    public static byte[] base64DecodeExt(String msg) {
        return Base64.decode(msg.getBytes(), Base64.DEFAULT);
    }

    // base解密
    public static String base64Decode(byte[] msg) throws Exception {
        return new String(Base64.decode(msg, Base64.DEFAULT));
    }

    // 判断当天是周几
    public static int dayForWeek() {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        int dayForWeek = 0;
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            dayForWeek = 7;
        } else {
            dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
        }
        return dayForWeek;
    }

    // 判断指定日期是周几
    public static int dayForWeek(String pTime) {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Calendar c = Calendar.getInstance();

        int dayForWeek = 0;
        try {
            c.setTime(format.parse(pTime));
            if (c.get(Calendar.DAY_OF_WEEK) == 1) {
                dayForWeek = 7;
            } else {
                dayForWeek = c.get(Calendar.DAY_OF_WEEK) - 1;
            }
        } catch (Exception e) {

        }
        return dayForWeek;
    }

    //返回某个日期前几天的日期
    public static long getFrontDay(Date date, int i) {
        Calendar cal = new GregorianCalendar();
        cal.setTime(date);
        cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
        return cal.getTime().getTime();
    }

    //返回某个日期前几天的日期
    public static Date getFrontDay(String day, int i) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date = sdf.parse(day);
            Calendar cal = new GregorianCalendar();
            cal.setTime(date);
            cal.set(Calendar.DATE, cal.get(Calendar.DATE) - i);
            return cal.getTime();
        } catch (Exception e) {
            return null;
        }

    }

    public static long getString4Long(String content, String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        try {
            Date date = format.parse(content);
            return date.getTime();
        } catch (Exception e) {
            return 0;
        }
    }

    // 判断时间是否属于指定的时间格式
    public static boolean isFormat(String content, String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        try {
            Date date = format.parse(content);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 判断时间是否属于指定的时间格式
    public static boolean isFormat(long content, String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        try {
            Date date = new Date(content);
            format.format(date);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    //第一个参数是要计算的字符串，第二个参数是字提大小
    public static float getTextWidth(String text, float Size) {
        TextPaint FontPaint = new TextPaint();
        FontPaint.setTextSize(Size);
        return FontPaint.measureText(text);
    }

    public static Bitmap getViewBp(View v) {
        if (null == v) {
            return null;
        }
        v.setDrawingCacheEnabled(true);
        v.buildDrawingCache();
        if (Build.VERSION.SDK_INT >= 11) {
            v.measure(View.MeasureSpec.makeMeasureSpec(v.getWidth(),
                    View.MeasureSpec.EXACTLY), View.MeasureSpec.makeMeasureSpec(
                    v.getHeight(), View.MeasureSpec.EXACTLY));
            v.layout((int) v.getX(), (int) v.getY(),
                    (int) v.getX() + v.getMeasuredWidth(),
                    (int) v.getY() + v.getMeasuredHeight());
        } else {
            v.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                    View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
            v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
        }
        Bitmap b = Bitmap.createBitmap(v.getDrawingCache(), 0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());

        v.setDrawingCacheEnabled(false);
        v.destroyDrawingCache();
        return b;
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @return boolean Returns "true" if all deletions were successful.
     * If a deletion fails, the method stops attempting to
     * delete and returns "false".
     */
    public static boolean deletesFile(File file) {
        String[] files = file.list();
        if (files != null && files.length > 0) {
            for (String f : files) {
                boolean success = deletesFile(new File(file, f));
                if (!success) {
                    return false;
                }
            }
        }
        return file.delete();
    }

    /**
     * 质量压缩方法
     *
     * @param image
     * @return
     */
    public static Bitmap compressImage(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 90;

        while (baos.toByteArray().length / 1024 > 100) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset(); // 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
        return bitmap;
    }

    /**
     * 图片按比例大小压缩方法
     *
     * @param image （根据Bitmap图片压缩）
     * @return
     */
    public static Bitmap compressScale(Bitmap image) {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos);

        // 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
        if (baos.toByteArray().length / 1024 > 1024) {
            baos.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 80, baos);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        // 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
        // float hh = 800f;// 这里设置高度为800f
        // float ww = 480f;// 这里设置宽度为480f
        float hh = 512f;
        float ww = 512f;
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放
        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) { // 如果高度高的话根据高度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be; // 设置缩放比例
        // newOpts.inPreferredConfig = Config.RGB_565;//降低图片从ARGB888到RGB565

        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        isBm = new ByteArrayInputStream(baos.toByteArray());
        bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);

        return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩

        //return bitmap;
    }

    /**
     * 获取某路径下的子文件
     */
    public static List<String> getSubFile(String fileName) {
        List<String> subFile = new ArrayList<>();
        String path = getSDPath() + "/" + fileName;
        File file = new File(path);
        //确保该路径存在
        if (file.exists()) {
            File[] tempList = file.listFiles();
            //有子文件时
            if (tempList.length > 0) {
                for (int i = 0; i < tempList.length; i++) {
                    //文件
                    if (tempList[i].isFile()) {
                        subFile.add(tempList[i].toString());
                    }
                }
            }
        }
        return subFile;
    }

    // 比较两天的时间间隔 (天数)
    public static int daysBetween(long date1, long date2) {
        long between_days = 0;
        if (date1 - date2 > 0) {
            between_days = (date1 - date2) / (1000 * 3600 * 24);
        } else {
            between_days = (date2 - date1) / (1000 * 3600 * 24);
        }

        return Integer.parseInt(String.valueOf(between_days));
    }

    public static String getFileType(String fileName) {
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        return prefix;
    }

    // 获取当前代码的行数
    public static String getLineInfo() {
        StackTraceElement ste = new Throwable().getStackTrace()[1];
        return ste.getFileName() + ":第" + ste.getLineNumber() + "行" + ",调用方法:" + ste.getMethodName();
    }

    //把后缀名转换为小写
    public static String suffixTo(String str) {
        int index = str.lastIndexOf(".");
        String subStr = str.substring(index + 1, str.length());

        subStr = subStr.toLowerCase();

        str = str.substring(0, index) + "." + subStr;
        return str;
    }

    public static String getManufacturer() {
        return Build.MANUFACTURER;
    }

    // str = 1关闭扬声器 str = 0 打开扬声器
    public static void setSpeaker(String content) {
        try {
            Log.d("setSpeaker", "content = " + content);
            method("/sys/bus/i2c/devices/2-0010/spk", content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void writeFile(String str) throws IOException, InterruptedException {

        File file = new File("/sys/bus/i2c/devices/2-0010/spk");
        file.setExecutable(true);
        file.setReadable(true);//设置可读权限
        file.setWritable(true);//设置可写权限
        if (str.equals("0")) {
            do_exec("busybox echo 0 > /sys/bus/i2c/devices/2-0010/spk");
        } else {
            do_exec("busybox echo 1 > /sys/bus/i2c/devices/2-0010/spk");
        }
    }

    // 写文件
    // "/sys/bus/i2c/devices/2-0010/spk"开关扬声器文件
    public static void method(String fileName, String content) {
        try {
            // 打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, false);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String do_exec(String cmd) {
        try {
            /* Missing read/write permission, trying to chmod the file */
            Process su;
            su = Runtime.getRuntime().exec("su");
            String str = cmd + "\n" + "exit\n";
            su.getOutputStream().write(str.getBytes());

            String result = inputStream2String(su.getInputStream());
            Log.d("do_exec", "result = \n" + result);

            if ((su.waitFor() != 0)) {
                LogUtils.e("cmd=" + cmd + " error!");
                throw new SecurityException();
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    public static void startApp(String packageName, String className) {
        do_exec("am start -n " + packageName + "/" + className);
    }

    public static void stopApp(String packageName) {

        do_exec("am force-stop " + packageName);
    }

    /**
     * 清除应用缓存的用户数据，同时停止所有服务和Alarm定时task
     * String cmd = "pm clear " + packageName;
     * String cmd = "pm clear " + packageName  + " HERE";
     * Runtime.getRuntime().exec(cmd)
     *
     * @param packageName
     * @return
     */
    public static Process clearAppUserData(String packageName) {
        Process p = execRuntimeProcess("pm clear " + packageName);
        if (p == null) {
            Log.d("clearAppUserData", "Clear app data packageName:" + packageName
                    + ", FAILED !");
        } else {
            Log.d("clearAppUserData", "Clear app data packageName:" + packageName
                    + ", SUCCESS !");
        }
        return p;
    }

    public static Process execRuntimeProcess(String commond) {
        Process p = null;
        try {
            p = Runtime.getRuntime().exec(commond);
        } catch (IOException e) {
            Log.d("execRuntimeProcess", "exec Runtime commond:" + commond + ", IOException" + e);
            e.printStackTrace();
        }
        Log.d("execRuntimeProcess", "exec Runtime commond:" + commond + ", Process:" + p);
        return p;
    }

    public static void startService4Hyphenate() {
        do_exec("am startservice -a com.hyphenate.chat.EMChatService");
        do_exec("am startservice -a com.hyphenate.chat.EMJobService");
    }

    public static void stopService4Hyphenate() {
        do_exec("am stopservice -a com.hyphenate.chat.EMChatService");
        do_exec("am stopservice -a com.hyphenate.chat.EMJobService");
    }

    public static int[] getRxAndTxBytes() {
        int result[] = new int[2];
        try {
            FileReader stream = new FileReader("/proc/net/xt_qtaguid/stats");
            BufferedReader in = new BufferedReader(stream, 500);

            String line;
            String[] dataStrings;
            while ((line = in.readLine()) != null) {
                dataStrings = line.split(" ");


                String applicationId = dataStrings[3];
                String uid = getUid() + "";
                String iface = dataStrings[1];
                String acct_tag_hex = dataStrings[2];

                String cntSet = dataStrings[4];
                if (uid.equals(applicationId)) {
//                    Log.d("getRxAndTxBytes","acct_tag_hex = "+acct_tag_hex);
                    if ("1".equals(cntSet) & "wlan0".equals(iface) & "0x0".equals(acct_tag_hex)) {
                        String arrays = Arrays.toString(dataStrings);
                        Log.d("getRxAndTxBytes", "arrays = " + arrays);
                        int rx_bytes = Integer.parseInt(dataStrings[5]);//总接受字节
                        int tx_bytes = Integer.parseInt(dataStrings[7]);//总发送字节
                        result[0] = rx_bytes;
                        result[1] = tx_bytes;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

    public static void setScreenRotation(String rotationStr) {

        int rotation = 0;// Surface.ROTATION_90;

        if (rotationStr.equals("0")) {

            rotation = Surface.ROTATION_0;

        } else if (rotationStr.equals("90")) {

            rotation = Surface.ROTATION_90;

        } else if (rotationStr.equals("180")) {

            rotation = Surface.ROTATION_180;

        } else if (rotationStr.equals("270")) {

            rotation = Surface.ROTATION_270;
        }

        Settings.System.putInt(x.app().getContentResolver(), Settings.System.USER_ROTATION, rotation);

    }

    public static int getRotation() {
        try {
            int r = Settings.System.getInt(x.app().getContentResolver(), Settings.System.USER_ROTATION);
            Log.d("getRotation", "getRotation = " + r);
            return r;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * @return 0、横屏 1、竖屏
     */
    public static int getScreenDirection() {
        int rotation = getRotation();
        if (rotation == 0 || rotation == 2) {
            return 0;
        } else if (rotation == 1 || rotation == 3) {
            return 1;
        } else {
            return 1;
        }
    }

    public static Date stringToDate(String strTime, String formatType)
            throws ParseException {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        date = formatter.parse(strTime);
        return date;
    }


    public static long stringToLong(String strTime, String formatType) {
        try {
            Date date = stringToDate(strTime, formatType); // String类型转成date类型
            if (date == null) {
                return 0;
            } else {
                long currentTime = dateToLong(date); // date类型转成long类型
                return currentTime;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }

    }

    public static long dateToLong(Date date) {
        return date.getTime();
    }

    public static List<String[]> genWeekList() {
        List<String[]> list = new ArrayList<>();
        String[] weekName = new String[]{"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String sdate = sdf.format(new Date());
            Date date = sdf.parse(sdate);

            Calendar cal = java.util.Calendar.getInstance();
            for (int i = 0; i < 7; i++) {
                String[] s = new String[2];
                cal.setTime(date);
                cal.add(Calendar.DATE, i);
                String sdatei = sdf.format(cal.getTime());
                s[0] = weekName[(cal.get(Calendar.DAY_OF_WEEK) - 1)];
                s[1] = sdatei;
                list.add(s);
            }

            return list;
        } catch (Exception e) {
            return list;
        }

    }

    /**
     * 获取当前应用uid
     */
    public static int getUid() {
        try {
            PackageManager pm = x.app().getPackageManager();
            ApplicationInfo ai = pm.getApplicationInfo(x.app().getPackageName(), PackageManager.GET_ACTIVITIES);
            return ai.uid;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public static boolean uninstallSlient(String packageName) {

        String cmd = "pm uninstall " + packageName;
        Process process = null;
        DataOutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;

        try {
            //卸载也需要root权限
            process = Runtime.getRuntime().exec("su");

            os = new DataOutputStream(process.getOutputStream());
            os.write(cmd.getBytes());
            os.writeBytes("\n");
            os.writeBytes("exit\n");

            os.flush();
            //执行命令
            process.waitFor();
            //获取返回结果
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();

            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s = successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine()) != null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {

                if (os != null) {
                    os.close();
                }

                if (process != null) {
                    process.destroy();
                }

                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        //显示结果
        Log.d("uninstallSlient", "成功消息：" + successMsg.toString() + "\n" + "错误消息: " + errorMsg.toString());
        String success = successMsg.toString();
        if ("Success".equals(success)) {
            return true;
        } else {
            return false;
        }
    }

    public static void setLaunch() {
        setValueToProp("persist.sys.sw.firstLaunch", "true");
    }

    public static String getLaunch() {
        return getValueFromProp("persist.sys.sw.firstLaunch");
    }

    // String packageBoot = Utils.getValueFromProp("persist.sys.packageboot");
    public static String getValueFromProp(String key) {
        String value = "";
        try {
            Class classType = Class.forName("android.os.SystemProperties");
            Method getMethod = classType.getDeclaredMethod("get", new Class[]{String.class});
            value = (String) getMethod.invoke(classType, new Object[]{key});
        } catch (Exception var4) {
            ;
        }

        return value;
    }

    //Utils.setValueToProp("persist.sys.packagerun","000");
    public static void setValueToProp(String key, String val) {
        try {
            Class classType = Class.forName("android.os.SystemProperties");
            Method e = classType.getDeclaredMethod("set", new Class[]{String.class, String.class});
            e.invoke(classType, new Object[]{key, val});
            String result = getValueFromProp(key);
            Log.d("setValueToProp", "result = " + result);
        } catch (ClassNotFoundException var4) {
            var4.printStackTrace();
        } catch (NoSuchMethodException var5) {
            var5.printStackTrace();
        } catch (InvocationTargetException var6) {
            var6.printStackTrace();
        } catch (Exception var7) {
            var7.printStackTrace();
        }

    }

    // 调节亮度
    public static void setScreenBritness(Context context, int brightness) {
        //先关闭系统的亮度自动调节
        try {
            if (android.provider.Settings.System.getInt(context.getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE) == android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                android.provider.Settings.System.putInt(context.getContentResolver(),
                        android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE,
                        android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
        } catch (Settings.SettingNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        //不让屏幕全暗
        if (brightness <= 1) {
            brightness = 1;
        }
        Uri uri = android.provider.Settings.System.getUriFor("screen_brightness");
        android.provider.Settings.System.putInt(context.getContentResolver(), "screen_brightness", brightness);
        // resolver.registerContentObserver(uri, true, myContentObserver);
        context.getContentResolver().notifyChange(uri, null);

    }

    // 获取亮度值
    public static int getBritness(Context context) {
        try {
            if (android.provider.Settings.System.getInt(context.getContentResolver(), android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE) == android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) {
                android.provider.Settings.System.putInt(context.getContentResolver(),
                        android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE,
                        android.provider.Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);
            }
        } catch (Settings.SettingNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        //获取当前亮度,获取失败则返回255
        int screenBrightness = Settings.System.getInt(context.getContentResolver(),
                Settings.System.SCREEN_BRIGHTNESS,
                255);

        return screenBrightness;
    }

    public static void setStreamVolume(Context context, int voice) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, voice, AudioManager.FLAG_PLAY_SOUND);
    }

    public static int getStreamVolume(Context context) {
        AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        return audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    }

    /**
     * 判断是否包含SIM卡
     *
     * @return 状态
     */
    public static boolean hasSimCard(Context context) {
        TelephonyManager telMgr = (TelephonyManager)
                context.getSystemService(Context.TELEPHONY_SERVICE);
        int simState = telMgr.getSimState();
        boolean result = true;
        switch (simState) {
            case TelephonyManager.SIM_STATE_ABSENT:
                result = false; // 没有SIM卡
                break;
            case TelephonyManager.SIM_STATE_UNKNOWN:
                result = false;
                break;
        }
        Log.d("hasSimCard", result ? "有SIM卡" : "无SIM卡");
        return result;
    }

    public static void setEthernetEnabled(Context context, boolean enable) {
        Log.d("Ethernet", "发送Ethernet开关广播");
        Intent intent = new Intent("com.ys.set_eth_enabled");
        intent.putExtra("eth_mode", enable);
        context.sendBroadcast(intent);
    }

    public static void setWifi(Context context, boolean isEnable) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        wifiManager.setWifiEnabled(isEnable);
    }

    public static void closeEthernet(Context context) {
        Intent intent = new Intent("com.vendor.interface.set.ethernet_disable");
        context.sendBroadcast(intent);
    }

    public static void openEthernet(Context context) {
        Intent intent = new Intent("com.vendor.interface.set.ethernet_enable");
        context.sendBroadcast(intent);
    }

    public static void hookWebView() {
        int sdkInt = Build.VERSION.SDK_INT;
        try {
            Class<?> factoryClass = Class.forName("android.webkit.WebViewFactory");
            Field field = factoryClass.getDeclaredField("sProviderInstance");
            field.setAccessible(true);
            Object sProviderInstance = field.get(null);

            if (sProviderInstance != null) {
                Log.d("hookWebView", "sProviderInstance isn't null");
                return;
            }

            Method getProviderClassMethod;

            if (sdkInt > 22) {

                getProviderClassMethod = factoryClass.getDeclaredMethod("getProviderClass");
            } else if (sdkInt == 22) {
                getProviderClassMethod = factoryClass.getDeclaredMethod("getFactoryClass");
            } else {
                Log.i("hookWebView", "Don't need to Hook WebView");
                return;
            }

            getProviderClassMethod.setAccessible(true);
            Class<?> providerClass = (Class<?>) getProviderClassMethod.invoke(factoryClass);
            Class<?> delegateClass = Class.forName("android.webkit.WebViewDelegate");
            Constructor<?> providerConstructor = providerClass.getConstructor(delegateClass);
            if (providerConstructor != null) {
                providerConstructor.setAccessible(true);
                Constructor<?> declaredConstructor = delegateClass.getDeclaredConstructor();
                declaredConstructor.setAccessible(true);
                sProviderInstance = providerConstructor.newInstance(declaredConstructor.newInstance());
                Log.d("hookWebView", "sProviderInstance:{} = " + sProviderInstance);
                field.set("sProviderInstance", sProviderInstance);
            }
            Log.d("hookWebView", "Hook done!");
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static boolean isTelephonyCalling() {
        boolean calling = false;
        TelephonyManager telephonyManager = (TelephonyManager) x.app().getSystemService(Context.TELEPHONY_SERVICE);
        if (TelephonyManager.CALL_STATE_OFFHOOK == telephonyManager.getCallState() || TelephonyManager.CALL_STATE_RINGING == telephonyManager.getCallState()) {
            calling = true;
        }
        return calling;
    }

    public static String isReplaceStr(String str_content) {
        String r = "";
        Pattern p = Pattern.compile("\\s*|\t|\r|\n");
        Matcher m = p.matcher(str_content);
        r = m.replaceAll("");
        return r;
    }

    // 发短信
    public static void sendSMS(Context context, String num, String content) {
        Log.d("sendSMS", "num = " + num + ",content = " + content);
        //处理返回的发送状态
        String SENT_SMS_ACTION = "SENT_SMS_ACTION";
        Intent sentIntent = new Intent(SENT_SMS_ACTION);
        PendingIntent sentPI = PendingIntent.getBroadcast(x.app(), 0, sentIntent, 0);
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context _context, Intent _intent) {
                switch (getResultCode()) {
                    case Activity.RESULT_OK:
//                        Toast.makeText(_context,  "短信发送成功", Toast.LENGTH_SHORT)  .show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        break;
                }
            }
        }, new IntentFilter(SENT_SMS_ACTION));

        //处理返回的接收状态
        String DELIVERED_SMS_ACTION = "DELIVERED_SMS_ACTION";
        // create the deilverIntent parameter
        Intent deliverIntent = new Intent(DELIVERED_SMS_ACTION);
        PendingIntent deliverPI = PendingIntent.getBroadcast(x.app(), 0, deliverIntent, 0);
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context _context, Intent _intent) {
//                Toast.makeText(_context,   "短信接收成功", Toast.LENGTH_SHORT)    .show();
            }
        }, new IntentFilter(DELIVERED_SMS_ACTION));


        SmsManager smsm = SmsManager.getDefault();
        ArrayList<String> divideContents = smsm.divideMessage(content);
        ArrayList<PendingIntent> pendingIntents = new ArrayList<>();
        pendingIntents.add(sentPI);
        ArrayList<PendingIntent> deliveryIntents = new ArrayList<>();
        deliveryIntents.add(deliverPI);
        if (content.length() > 70) {
            for (String msg : divideContents) {
                smsm.sendTextMessage(num, null, msg, sentPI, deliverPI);
            }
        } else {
            smsm.sendMultipartTextMessage(num, null, divideContents, pendingIntents, deliveryIntents);
        }

    }

    public static int getChronometerSeconds(String times) {
        if (Utils.isEmpty(times)) return 0;
        int totalss = 0;
        if (times.length() == 7) {

            String[] split = times.split(":");
            String string2 = split[0];
            int hour = Integer.parseInt(string2);
            int Hours = hour * 3600;
            String string3 = split[1];
            int min = Integer.parseInt(string3);
            int Mins = min * 60;
            int SS = Integer.parseInt(split[2]);
            totalss = Hours + Mins + SS;
        } else if (times.length() == 5) {

            String[] split = times.split(":");
            String string3 = split[0];
            int min = Integer.parseInt(string3);
            int Mins = min * 60;
            int SS = Integer.parseInt(split[1]);

            totalss = Mins + SS;
        }
        String time = totalss + "";
        Log.d("getChronometerSeconds", "time = " + time);
        return totalss;


    }

    public static boolean isLatestWeek(Date addtime, Date now) {
        Calendar calendar = Calendar.getInstance();  //得到日历
        calendar.setTime(now);//把当前时间赋给日历
        calendar.add(Calendar.DAY_OF_MONTH, 7);  //设置为7天后
        Date after7days = calendar.getTime();   //得到7天前的时间

        if (after7days.getTime() < addtime.getTime()) {
            return true;
        } else {
            return false;
        }
    }

    // 刷卡之后获取卡好
    public static String getCardNum(String data) {
        writeToSdCard(data, "data.txt", true);
        String[] cardNums = data.split(" ");
        String strHex = "";
        String model = Build.MODEL;
        if (cardNums != null && cardNums.length > 0) {
            if ("M3".equals(model) || "SoftwinerEvb".equals(model)) {
                if (cardNums.length >= 9) {
                    if ("08".equals(cardNums[3])) {
                        if (cardNums.length >= 12) {
                            strHex = cardNums[11] + cardNums[10] + cardNums[9] + cardNums[8];
                        }
                    } else if ("00".equals(cardNums[3])) {
                        if (cardNums.length >= 16) {
                            strHex = cardNums[14] + cardNums[13] + cardNums[12] + cardNums[11] + cardNums[10] + cardNums[9] + cardNums[8];
                        }
                    }
                }
            } else if ("ZK-R329".equals(model)) {
                if (cardNums.length >= 7) {
                    strHex = cardNums[5] + cardNums[4] + cardNums[3] + cardNums[2];
                }
            } else if ("rk3188".equals(model)) {
                if (cardNums.length >= 9) {
                    strHex = cardNums[3] + cardNums[4] + cardNums[5] + cardNums[6];
                }
            } else {
                if (cardNums.length >= 9) {
                    if ("01".equals(cardNums[2])) {//IC卡
                        strHex = cardNums[3] + cardNums[4] + cardNums[5] + cardNums[6];
                    } else if ("02".equals(cardNums[2])) {//ID卡
                        strHex = /*cardNums[3] + */cardNums[4] + cardNums[5] + cardNums[6] + cardNums[7];
                    }
                } else {
                    return "";
                }
            }
        }
        if (!Utils.isEmpty(strHex)) {
            String cardNum = new BigInteger(strHex, 16).toString();
            cardNum = padLeft(cardNum, 10);
            Log.d("getCardNum", "cardNum = " + cardNum);
            return cardNum;
        } else {
            return "";
        }
    }

    public static String padLeft(String s, int length) {
        byte[] bs = new byte[length];
        byte[] ss = s.getBytes();
        Arrays.fill(bs, (byte) (48 & 0xff));
        System.arraycopy(ss, 0, bs, length - ss.length, ss.length);
        return new String(bs);
    }

    public static int getMipMapResource(String imageName) {
        int version = Utils.getAndroidSDKVersion();
        int resId = 0;
        if (version >= Build.VERSION_CODES.KITKAT) {
            Context ctx = x.app();
            resId = ctx.getResources().getIdentifier(imageName, "mipmap", ctx.getPackageName());
            //如果没有在"mipmap"下找到imageName,将会返回0
        } else {
            Class mipmap = R.mipmap.class;
            Field field = null;
            try {
                field = mipmap.getField(imageName);
                resId = field.getInt(field.getName());
            } catch (Exception e) {
                resId = R.mipmap.w_999;
                Log.e("ERROR", "PICTURE NOT　FOUND！");
            }
        }
        return resId;
    }

    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /**
     * 文件转Base64.
     *
     * @param filePath
     * @return
     */
    public static String file2Base64(String filePath) {
        FileInputStream objFileIS = null;
        try {
            objFileIS = new FileInputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
        byte[] byteBufferString = new byte[1024];
        try {
            for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1; ) {
                objByteArrayOS.write(byteBufferString, 0, readNum);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        String videodata = Base64.encodeToString(objByteArrayOS.toByteArray(), Base64.DEFAULT);
        return videodata;
    }

    public static void shot() {
//        DisplayManager.
        try {
            final String filePath = "/mnt/sdcard" + "/shot/shot.jpg";
            File file = new File(filePath);
            Log.d("ShellUtils", "parent = " + file.getParentFile().toString());
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            ScreentShotUtil.getInstance().takeScreenshot(x.app(), filePath);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static String rotateBitmap(String path) {
        ExifInterface exifInterface = null;
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        try {
            exifInterface = new ExifInterface(path);
        } catch (IOException e) {
            e.printStackTrace();
            exifInterface = null;
        }


        int digree = 0;

        if (exifInterface != null) {
            // 读取图片中相机方向信息
            int ori = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);

            // 计算旋转角度

            switch (ori) {

                case ExifInterface.ORIENTATION_ROTATE_90:
                    digree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    digree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    digree = 270;
                    break;
                default:
                    digree = 90;
                    break;

            }
        }

        Log.d("rotateBitmap", "digree = " + digree);
        if (digree != 0) {
            // 旋转图片
            Matrix m = new Matrix();
            m.postRotate(digree);

            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), m, true);


            saveBitmap(path, bitmap);

            return path;
        } else {
            return "";
        }
    }

    /**
     * 保存方法
     */

    public static void saveBitmap(String path, Bitmap bm) {
        File f = new File(path);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            if (null != bm) {
                bm.recycle();
            }
            out.flush();
            out.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public static void copyFile(String oldPath, final String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    fs.write(buffer, 0, byteread);
                }


                inStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 判断app是否在前台运行
    public static boolean isTopActivity(String packageName) {

        ActivityManager activityManager = (ActivityManager) x.app()
                .getSystemService(Context.ACTIVITY_SERVICE);

        List<ActivityManager.RunningAppProcessInfo> list = activityManager.getRunningAppProcesses();
        if (list.size() == 0) return false;
        for (ActivityManager.RunningAppProcessInfo process : list) {
            String processName = process.processName;

//            LogUtils.e("processName = "+processName);

            if (process.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                    && processName.equals(packageName)) {
//                Log.d("isTopActivity",Utils.getLineInfo()+",processName = "+processName+",packageName = "+packageName);
                return true;
            }
        }
        return false;

    }

//    public static void uploadLog() {
//        String code = getDevCode();
//        String path = getSDPath() + "/eton"+ "/Log1.txt";
//        AVFile file = new AVFile(code,new File(path));
//
//        file.saveInBackground(new ProgressCallback() {
//            @Override
//            public void done(Integer percentDone) {
//
//            }
//        });
//    }

    public static void getLog() {
        //第一个是Logcat ，也就是我们想要获取的log日志
        //第二个是 -s 也就是表示过滤的意思
        //第三个就是 我们要过滤的类型 W表示warm ，我们也可以换成 D ：debug， I：info，E：error等等
//        String[] running = new String[]{"logcat","","adb logcat"};
        String[] running = new String[]{"logcat", "-v", "time"};

        final String path = getSDPath() + "/eton";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            Process exec = Runtime.getRuntime().exec(running);

            final InputStream is = exec.getInputStream();

            new Thread() {
                @Override
                public void run() {
                    FileOutputStream os = null;
                    try {
                        //新建一个路径信息
                        String fileName = path + "/Log.txt";
                        os = new FileOutputStream(fileName);
                        int len = 0;
                        byte[] buf = new byte[1024];
                        while (-1 != (len = is.read(buf))) {
                            os.write(buf, 0, len);
                            os.flush();
                        }
                    } catch (Exception e) {
                        Log.d("writelog",
                                "read logcat process failed. message: "
                                        + e.getMessage());
                    } finally {
                        if (null != os) {
                            try {
                                os.close();
                                os = null;
                            } catch (IOException e) {
                                // Do nothing
                            }
                        }
                    }
                }
            }.start();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    public static void getLog1() {
        //第一个是Logcat ，也就是我们想要获取的log日志
        //第二个是 -s 也就是表示过滤的意思
        //第三个就是 我们要过滤的类型 W表示warm ，我们也可以换成 D ：debug， I：info，E：error等等
        int myPid = android.os.Process.myPid();
        String[] running = new String[]{"logcat", "", "adb logcat --pid=" + myPid};

        final String path = getSDPath() + "/eton";
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }

        try {
            Process exec = Runtime.getRuntime().exec(running);

            final InputStream is = exec.getInputStream();

            new Thread() {
                @Override
                public void run() {
                    FileOutputStream os = null;
                    try {
                        //新建一个路径信息
                        String fileName = path + "/Log1.txt";
                        os = new FileOutputStream(fileName);
                        int len = 0;
                        byte[] buf = new byte[1024];
                        while (-1 != (len = is.read(buf))) {
                            os.write(buf, 0, len);
                            os.flush();
                        }
                    } catch (Exception e) {
                        Log.d("writelog",
                                "read logcat process failed. message: "
                                        + e.getMessage());
                    } finally {
                        if (null != os) {
                            try {
                                os.close();
                                os = null;
                            } catch (IOException e) {
                                // Do nothing
                            }
                        }
                    }
                }
            }.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static int getWeekNum() {

        int week = 0;
        Calendar c = Calendar.getInstance();
        try {
            c.setTime(new Date());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 1) {
            week = 7;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 2) {
            week = 1;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 3) {
            week = 2;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 4) {
            week = 3;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 5) {
            week = 4;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 6) {
            week = 5;
        }
        if (c.get(Calendar.DAY_OF_WEEK) == 7) {
            week = 6;
        }

        return week;
    }

    public static void upload(String schoolName) {
        String devcode = getDevCode();
        String path = getSDPath() + "/eton" + "/Log.txt";
//        AVFile file = new AVFile(schoolName + "_" + devcode, new File(path));
//        file.saveInBackground(new ProgressCallback() {
//            @Override
//            public void done(Integer percentDone) {
//                LogUtils.e("percentDone = " + percentDone);
//            }
//        });
    }

    /**
     * 判断某个界面是否在前台,返回true，为显示,否则不是
     */
    public static boolean isForeground(String className) {
        if (TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) x.app().getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }


    public static Bitmap byteToBitmap(byte[] imgByte) {
        InputStream input = null;
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 2;
        input = new ByteArrayInputStream(imgByte);
        SoftReference softRef = new SoftReference(BitmapFactory.decodeStream(
                input, null, options));
        bitmap = (Bitmap) softRef.get();
        if (imgByte != null) {
            imgByte = null;
        }
        try {
            if (input != null) {
                input.close();
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block  
            e.printStackTrace();
        }
        return bitmap;
    }
}
